/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// @ts-nocheck
import router from '@system.router';
import prompt from '@system.prompt';
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility';
import http from '@ohos.net.http';
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import request from '@ohos.request';
import file from '@system.file';
//音频_工具
import process from '@ohos.process'
import logger from '../../common/Logger'
import { prepareFdNumber } from '../../common/Util'
import { Util, updateTime, PATH } from '../../common/Util'
//录音
import { RecordModel } from '../../common/RecordModel'
//播放
import { AudioModel } from '../../common/AuidoModel'

const TAG = '[dialogPages]'
const MILLISECOND = 1000

export default {
    data: {
        isAudio: false,
        audioMsg: '点击说话',
        inputMsg: '',
        showMore: false,
        showFace: false,
        smiling:'',
        addToken:"11111",
        uid:'',
        groupId: '',
        idx: 0,
        msg:'',
        title:'',
        deleteOrRecall:"删除",
        Recall:"撤回",
        deleteA:"删除",
        imgUrl:'',
        result:'111',
        code:"111",
        header:"111",
        user:{
            code:"",
            msg:"",
            data:""
        },
        timeoutmsg:'',
        message:'',
        moreBtnUrl: '/common/images/more.png',
        faceBtnUrl: '/common/images/face.png',
        MsgList: [],
        //创建一个数组来保存图片的路径
		imgArr: ["撤回", "删除"],
        //创建一个变量，用来保存当前的索引
        index: 0,
        list:[],
        fresh:false,
        globalX: 0, //落点x轴
        globalY: 0, //落点y轴
        touchId: 0,
        //初始化刷新次数
        num: 0,
        //没有会话的情况下的参数
        noSession: 0,
        //音频文件数据
        recordModel: new RecordModel(),
        audioModel: new AudioModel(),
        isPlay: false,
        mainData: {
            file: '',
            path: '',
            date: '',
            dataTime: '00:00',
            hasSend: true,
        },
        audioConfig: {
            audioSourceType: 1,
            audioEncoder: 3,
            audioEncodeBitRate: 22050,
            audioSampleRate: 22050,
            numberOfChannels: 2,
            format: 2,
            uri: ''
        },
        util: new Util(),
        resultFile: 'default',
        isRecord: false,
        timer: undefined,
        timerPlay: undefined,
        millisecond: 0,
        millisecondPlay: 0,
        dataTime: '00:10',
        timePlay: '00:00',
        //选中的表情
        selectFaceContent:'',
        downloadFileList: [],
        textInputDisabled: false,
        textInputPlaceholder: "",
        sendBtnDisabled: false,
        isTalkForbidden: false,
        groupLevel: 2,
    },
    onInit(){
        console.info('dialogPages=====onInit')
        let context = featureAbility.getContext()
        context.requestPermissionsFromUser(['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA','ohos.permission.INTERNET'], 666,(result) => {
            console.info('dialogPages=====requestPermissionsFromUserresult:' + JSON.stringify(result));
        })
    },
    onShow(){
        console.log('dialogPages=====getParams', JSON.stringify(router.getParams()));
        this.jumpMode();
        //更新消息
        this.refreshMsg();
        this.deleteOrRecall = this.$app.$def.deleteOrRecall;
        this.groupId = this.$app.$def.chatData[this.idx].uid[0]
        this.getToken();
        this.uid =  this.$app.$def.uid;
        /*if(this.$app.$def.connectStatus==0){
            socket.connect("192.168.1.110",1884);
            this.$app.$def.connectStatus=1;
        }*/
//        setInterval(this.socketReceive ,2000);
        if((this.$app.$def.uri.length==1 && this.$app.$def.uri[0]==1) || (this.$app.$def.uri.length==0)){
            this.$app.$def.uri = [];
        }else{

            for (var i = 0; i < this.$app.$def.uri.length; i++) {
                this.MsgList.push({isMe: true,
                    sendUid:"",
                    messageType: 1,
                    content: this.$app.$def.uri[i],
                    profPicUrl:'/common/images/my.jpg',
                    createTime:""});
                this.inputMsg = '';
                this.$element('chatList').scrollBottom(true);
                this.MsgList.push({isMe: false,
                    sendUid:"",
                    messageType: 0,
                    content: "你好！",
                    profPicUrl:'/common/images/bob.jpg',
                    createTime:""});
            }

            this.$app.$def.uri=[];
        }
        this.verify()
    },
    verify() {
        console.info("dialogPages=====verify:");
        if(this.$app.$def.chatData[this.idx].unRead == 'group'){
            //检查群组是否存在
            console.info("dialogPages=====verifyr group:"+this.groupId);
            let httpRequest= http.createHttp();
            let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/exist/" + this.groupId, {
                connectTimeout: 60000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            });
            promise.then((value) => {
                let re = JSON.parse(value.result.toString())
                console.info('dialogPages====>exist:'+JSON.stringify(re))
                if(re.code == 2026) {
                    this.MsgList.push({isMe: false,
                        sendUid:"",
                        messageType: 0,
                        content: "当前群聊已解散",
                        isDismiss: true,
                        profPicUrl:'',
                        createTime:"",});
                    this.textInputDisabled = true
                    this.sendBtnDisabled = true
                    this.textInputPlaceholder = "群聊已解散"
                } else if(re.code == 2025) {
                    console.info('dialogPages====>exist:群组存在')
                    this.checkIsTalkForbidden(); //群组存在的话，检查群组是否被禁言了
                }
            }).catch((err) => {
                console.error(`dialogPages====>verifyr group: errCode:${err.code}, errMessage1:${err.data}`);
            });
        }else if(this.$app.$def.chatData[this.idx].unRead == 'say'){
            console.info("dialogPages=====verifyr say:"+ this.$app.$def.chatData[this.idx].uid[0]);
            let httpRequest= http.createHttp();
            let promise = httpRequest.request("http://" + this.$app.$def.ip +"/user/isFriend", {
                method: 'POST',
                extraData:JSON.stringify({"uid":this.$app.$def.uid, "touid":this.$app.$def.chatData[this.idx].uid[0]}),
                connectTimeout: 60000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            });
            promise.then((value) => {
                let re = JSON.parse(value.result.toString())
                console.info('dialogPages====>say exist:'+JSON.stringify(re))
                if(re.code == 2048) {
                    this.MsgList.push({isMe: false,
                        sendUid:"",
                        messageType: 0,
                        content: "你们已经不是好友了",
                        isDismiss: true,
                        profPicUrl:'',
                        createTime:""});
                    this.textInputDisabled = true
                    this.sendBtnDisabled = true
                    this.textInputPlaceholder = "请先添加对方"
                } else if(re.code == 2047) {
                    console.info('dialogPages====>exist:好友存在')
                }
            }).catch((err) => {
                console.error(`dialogPages====>say exist: errCode:${err.code}, errMessage1:${err.data}`);
            });
        }
    },
    checkIsTalkForbidden(){
        console.log('dialogPages=====checkIsTalkForbidden')
        //        TODO  未完成
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/isForbidden", {
            method: 'POST',
            extraData:JSON.stringify({"uid":this.$app.$def.uid, "groupId":this.groupId}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re = JSON.parse(value.result.toString())
            if(re.code == 2042){
                console.info('群组未被禁言');
                this.isTalkForbidden = false;
                // 禁言状态改变
                this.textInputDisabled = false
                this.sendBtnDisabled = false
                this.textInputPlaceholder = ""
            } else if(re.code == 2041){
                console.info('群组已被禁言');
                this.verifyUserPrivilege(); //群被禁言的话，检查本用户是不是群主或管理员
                this.isTalkForbidden = true;
            }
        }).catch((err) => {
            console.error(`checkIsTalkForbidden====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    verifyUserPrivilege(){
        //获取群内等级，以此针对性展示页面
        console.log('dialogPages=====verifyUserPrivilege')
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/getUserPrivilege", {
            method:'POST',
            extraData:JSON.stringify({
                "uid":this.$app.$def.uid,
                "groupId":this.groupId
            }),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re  = JSON.parse(value.result.toString())
            console.info('groupChatMessage====>groupPrivilege: '+re.data)
            if(re.code == 200) {
                this.groupLevel = re.data
                if(re.data === 0){ // 本账号为群主
                    this.textInputDisabled = false
                    this.sendBtnDisabled = false
                    this.textInputPlaceholder = ""
                }
                else if(re.data === 1){ // 本账号为管理员
                    this.textInputDisabled = false
                    this.sendBtnDisabled = false
                    this.textInputPlaceholder = ""
                }
                else if(re.data === 2){ // 本账号为群成员
                    this.textInputDisabled = true
                    this.sendBtnDisabled = true
                    this.textInputPlaceholder = "群组全体禁言"
                }
            }
        }).catch((err) => {
            prompt.showToast({
                message: '群等级未获取成功，网络',
                duration: 2000,
            });
            console.error(`groupChatMessage====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    //跳转到会话页面的两种方式
    jumpMode(){
        console.log('dialogPages=====jumpMod');
        this.noSession = 0;
        //通讯录跳转
        if(router.getParams() && router.getParams().type && router.getParams().type === 'createGroup'){
            console.log('dialogPages=====from createGroup');
            this.$app.$def.idx = 0
            this.idx = this.$app.$def.idx;
            this.imgUrl = this.$app.$def.chatData[this.idx].imgUrl;
            this.title = this.$app.$def.chatData[this.idx].title
        } else if(this.$app.$def.mailFriendId != -1 && router.getParams().sayOrGroup !== 'group')
        {
            console.info('dialogPages=====from mail say')
            this.mailFriend()
            this.$app.$def.mailFriendId = -1
        } else if(this.$app.$def.mailFriendId != -1 && router.getParams().sayOrGroup === 'group')
        {
            console.info('dialogPages=====from mail group')
            this.mailGroup()
            this.$app.$def.mailFriendId = -1
        }//列表页面跳转
        else{
            console.info('dialogPages=====from sessionlist')
            this.idx = this.$app.$def.idx;
            this.imgUrl = this.$app.$def.chatData[this.idx].imgUrl;
            this.title = this.$app.$def.chatData[this.idx].title;
        }

    },
    mailGroup() {
        var mailId = this.$app.$def.mailFriendId;
        console.info("dialogPages=====jumpMode---mailId:" + mailId);
        var mailUid = this.$app.$def.groupList[mailId].text
        console.info("dialogPages=====jumpMode---mailUid:" + mailUid);
        var length = this.$app.$def.chatData.length;
        console.info("dialogPages=====jumpMode---length:" + length);
        for(var i = 0;i < length; i++){
            var chatUid = this.$app.$def.chatData[i].uid;
            console.info("dialogPages=====jumpMode---i:" + i);
            console.info("dialogPages=====jumpMode---chatUid:" + chatUid);
            //判断从通讯录是否能找到该会话，如果可以，则选择；不可以，则新增。
            if(mailUid == chatUid[0] && this.$app.$def.chatData[i].unRead === router.getParams().sayOrGroup){
                console.info("dialogPages=====jumpMode---mailUid == chatUid[0]");
                this.idx = i;
                this.$app.$def.idx = i;
                this.noSession = 0;
                break;
            }
            else{
                console.info("dialogPages=====jumpMode---mailUid != chatUid[0]");
                //                    this.addSession(mailUid);
                this.noSession = 1;
            }
        }
        //如果没有匹配到已有session，则设置noSession为1，且设置idx并插入一行
        if(this.noSession == 1){
            this.idx = 0;
            this.addSession(mailUid);
        }
        console.info("dialogPages=====jumpMode---this.idx:" + this.idx);
        console.info("dialogPages=====jumpMode---this.unread:" + this.$app.$def.chatData[this.idx].unRead);
        this.imgUrl = this.$app.$def.chatData[this.idx].imgUrl;
        this.title = this.$app.$def.chatData[this.idx].title;
    },
    mailFriend(){
        var mailId = this.$app.$def.mailFriendId;
        console.info("dialogPages=====jumpMode---mailId:" + mailId);
        var mailUid = this.$app.$def.friendsList[mailId].id
        console.info("dialogPages=====jumpMode---mailUid:" + mailUid);
        var length = this.$app.$def.chatData.length;
        console.info("dialogPages=====jumpMode---length:" + length);
        for(var i = 0;i < length; i++){
            var chatUid = this.$app.$def.chatData[i].uid;
            console.info("dialogPages=====jumpMode---i:" + i);
            console.info("dialogPages=====jumpMode---chatUid:" + chatUid[0]);
            //判断从通讯录是否能找到该会话，如果可以，则选择；不可以，则新增。
            if(mailUid == chatUid[0] && this.$app.$def.chatData[i].unRead ===router.getParams().sayOrGroup){
                console.info("dialogPages=====jumpMode---mailUid == chatUid[0]");
                this.idx = i;
                this.$app.$def.idx = i;
                this.noSession = 0;
                break;
            }
            else{
                console.info("dialogPages=====jumpMode---mailUid != chatUid[0]");
                //                    this.addSession(mailUid);
                this.noSession = 1;
            }
        }
        //如果没有匹配到已有session，则设置noSession为1，且设置idx并插入一行
        if(this.noSession == 1){
            this.idx = 0;
            this.addSession(mailUid);
        }
        console.info("dialogPages=====jumpMode---this.idx:" + this.idx);
        console.info("dialogPages=====jumpMode---this.unread:" + this.$app.$def.chatData[this.idx].unRead);
        this.imgUrl = this.$app.$def.chatData[this.idx].imgUrl;
        this.title = this.$app.$def.chatData[this.idx].title;
    },
    //从通讯录进入一个没有会话的好友，会话页面增加新会话
    addSession(mailUid){
        console.info('dialogPage=====sayOrGroup:'+ router.getParams().sayOrGroup)
        let img = '/common/images/sessionPic/img_' + Math.round(Math.random() * 7 + 1) + '.png'
        let newSession = {
            'title': mailUid,
            'topMessage': '你们已经成为好友了',
            'imgUrl': img,
            'readTime': new Date().getHours() + ':' + new Date().getMinutes(),
            'unRead': router.getParams().sayOrGroup,
            'uid': [mailUid],
            'checkId': [],
            'MsgList': [{isMe: false,
                            sendUid:"",
                            messageType: 0,
                            content:'华为鸿蒙系统是一款全新的面向全场景的分布式操作系统，创造一个超级虚拟终端互联的世界',
                            profPicUrl:'/common/images/bob.jpg',
                            createTime:"",},
                        {isMe: false,
                            sendUid:"",
                            messageType: 1,
                            content:'/common/images/harmonyos.jpg',
                            profPicUrl:'/common/images/bob.jpg',
                            createTime:"",}]
        }
        this.$app.$def.chatData = [newSession, ...this.$app.$def.chatData]
    },
    sendRecord() {
        logger.info(`${TAG} enter sendRecord`)
        //todo http上传
        //todo tcp发消息
        logger.info(`${TAG} sendRecord mainData ${JSON.stringify(this.mainData)}`)
        //定时器，撤回转删除
        this.index = 0;
        this.changeState();
        let timestamp = new Date().getTime().toString() - 28800000
        this.MsgList.push({isMe: true,
            sendUid:"",
            messageType: 'audio',
            content: JSON.parse(JSON.stringify(this.mainData)),
            profPicUrl:'',
            createTime:timestamp});
        let srcPath = 'internal://cache/' + this.mainData.file + '.wav'
        let file1 = { filename: this.$app.$def.uid +'-'+ this.mainData.path, name: 'audio', uri: srcPath, type: "wav" };
        let data = {  };
        let header = { };
        let audioId = this.guid()
        let uploadTask;
        let myurl = "http://" + this.$app.$def.ip +"/file/audioUpload?audioSignature=" + audioId + "&uid=" +this.$app.$def.uid + "&audioType=" +this.$app.$def.chatData[this.idx].unRead
        console.info("dialogPages=====sendRecord myurl:" + myurl);
        let _this = this
        request.upload({ url: myurl, header: header, method: "POST", files: [file1], data: [data] }).then((data) => {
            uploadTask = data;
            uploadTask.on('headerReceive', function callback(headers){
                console.info("dialogPages=====upOnHeader headers:" + JSON.stringify(headers));
                _this.sendAudio(audioId, timestamp)
            });
            uploadTask.on('progress', function callback(uploadedSize, totalSize) {
                console.info("dialogPages=====upload totalSize:" + totalSize + "  uploadedSize:" + uploadedSize);
            });
        }).catch((err) => {
            console.info('dialogPages=====Failed to request the upload. Cause: ' + JSON.stringify(err));
        })
    },
    sendAudio(audioId, timestamp) {
//        let timestamp = new Date().getTime().toString() - 28800000
        let obj = {}
        let json = {}
        if(this.$app.$def.chatData[this.idx].unRead == 'say'){
            console.info("dialogPages====>sendAudio:type == say " );
            obj = { uid: this.uid, touid: this.$app.$def.chatData[this.idx].uid , role:'ho_user' , type:'say', content:audioId, stype:3,timestamp:timestamp};
            json = JSON.stringify(obj);
            console.info("dialogPages====>sendAudio:json == " + json);
        }
        else if(this.$app.$def.chatData[this.idx].unRead == 'group'){
            console.info("dialogPages====>sendAudio:type == group " );
            obj = { uid: this.uid, touid: [this.groupId] , role:'ho_user' , type:'group', content:audioId, stype:3,timestamp:timestamp};
            json = JSON.stringify(obj);
            console.info("dialogPages====>sendAudio:json == " + json);
        }
        this.$app.$def.mySocket.send(json)
    },
    //录音相关
    clickRecord() {
        logger.info(`${TAG} enter clickRecord`)
        if (!this.isRecord) {
            this.mainData.hasSend = false
            this.createFile()
            //开始录音
            let fdPath = prepareFdNumber(this.mainData.path)
            fdPath.then((fdNumber) => {
                logger.info(`${TAG} fdNumber= ${fdNumber}`)
                this.startRecorder(fdNumber)
                logger.info(`${TAG} startRecorder end`)
            })
        }
    },
    startRecorder(pathNumber) {
        this.audioConfig.uri = pathNumber
        logger.info(`${TAG} uri= ${this.audioConfig.uri}`)
        this.recordModel.initAudioRecorder()
        // 开始录音
        this.recordModel.startRecorder(this.audioConfig, ()=>{
            logger.info(`${TAG} enter the startRecorder callback`)
            this.isRecord = true
            this.timer = setInterval(() => {
                logger.info(`${TAG} enter the setInterval`)
                this.millisecond += MILLISECOND
                this.dataTime = updateTime(this.millisecond)
            }, MILLISECOND)
        })
    },
    stopRecorder() {
        clearInterval(this.timer)
        //停止录音
        this.recordModel.stopRecorder(() => {
            logger.info(`${TAG} enter callback isRecord= ${this.isRecord}`)
            if (this.isRecord) {
                this.isRecord = false
                logger.info(`${TAG} pause isRecord= ${this.isRecord}`)
                this.mainData.dataTime = this.dataTime
                logger.info(`${TAG} mainData = ${JSON.stringify(this.mainData)}`)
                this.util.put(this.mainData)
                logger.info(`${TAG} put end`)
                this.millisecond = 0
            }
        })
        logger.info(`${TAG} Stop success`)
    },
    createFile() {
        logger.info(`${TAG} enter createFile`)
        let time = new Date()
        let year = time.getFullYear()
        let month = this.complementNum(time.getMonth() + 1)
        let day = this.complementNum(time.getDate())
        let hour = this.complementNum(time.getHours())
        let minute = this.complementNum(time.getMinutes())
        let second = this.complementNum(time.getSeconds())
        this.mainData.file = `${year}${month}${day}_${hour}${minute}${second}`
        logger.info(`${TAG} file:  ${this.mainData.file}`)
        this.mainData.path = `${PATH}${this.mainData.file}.wav`
        logger.info(`${TAG} Path: ${this.mainData.path}`)
        var child = process.runCmd(`touch ${this.mainData.path};chmod -R 777 ${this.mainData.path}`)
        this.resultFile = child == null ? 'failed' : 'succeed'
        logger.info(`${TAG} runCmd= ${this.resultFile}`)
        var result
        if(child) {
            result = child.wait()
            result.then(val => {
                this.resultFile = `child process run finish${JSON.stringify(val)}`
            })
        }
        this.mainData.date = `${year}/${month}/${day}`
        logger.info(`${TAG} createFile OK`)
    },
    playNetworkAudio(item){
        let index = item.content.path.lastIndexOf("\/")
        let fileName = item.content.path.substring(index + 1, item.content.path.length);
        let filePath = '/data/storage/el2/base/haps/entry/files/' + Date.now().toString() + '_' + fileName
        let downloadConfig = {
            url: item.content.path, // 下载地址
            header: {},                               // 下载请求Header
            enableMetered: true,                      // 允许下载
            enableRoaming: true,                      // 允许下载
            filePath: filePath,                       // 本地文件路径
            networkType: request.NETWORK_WIFI         // WIFI网络下载
        }
        logger.info(`${TAG} url：${item.content.path}`)
        logger.info(`${TAG} filePath：${filePath}`)
        let downloadTask;
        let _this = this
        request.download(downloadConfig, (err, data) => {
            logger.info(`${TAG} err：${JSON.stringify(err)}`)
            logger.info(`${TAG} data：${JSON.stringify(data)}`)
            if (err) {
                console.info('dialogPages====Failed to request the download. Cause: ' + JSON.stringify(err));
                return;
            }
            downloadTask = data;
            console.info('dialogPages====downloadImage get downloadTask');
            //下载完成
            console.info('dialogPages====ready to on complete');
            downloadTask.on('complete', function callback() {
                console.info('dialogPages====Download task completed.');
                let audio = {
                    content: { path: filePath }
                }
                console.info('dialogPages====ready to play:' + filePath);
                _this.playAudio(audio)
            });
            //下载失败
            console.info('dialogPages====ready to on fail');
            downloadTask.on('fail', function callBack(err) {
                console.info('dialogPages====Download task failed. Cause:' + err);
            });
            //下载进度
            console.info('dialogPages====ready to on process');
            downloadTask.on('progress', function download_callback(receivedSize, totalSize) {
                console.info("dialogPages====download receivedSize:" + receivedSize + " totalSize:" + totalSize);
            });
            console.info('dialogPages====downloadImage end');
        });
    },
    //播放相关
    playAudio(item){
        logger.info(`${TAG} enter playAudio ${JSON.stringify(item.content)}`)
        //播放item.content.path
        if(!this.isPlay) {
            this.audioModel.initAudioPlayer(item.content.path, true)
            prompt.showToast({
                message: '开始播放',
                duration: 2000,
            })
            logger.info(`${TAG} playAudio initAudioPlayer success`)
            logger.info(`${TAG} playAudio start play`)
            this.timerPlay = setInterval(() => {
                this.millisecondPlay += MILLISECOND
                this.timePlay = updateTime(this.millisecondPlay)
                this.isPlay = true
                this.audioModel.onFinish(() => {
                    this.timePlay = '00:00'
                    this.millisecondPlay = 0
                    this.isPlay = false
                    clearInterval(this.timerPlay)
                })
            }, MILLISECOND)
        } else {
            prompt.showToast({
                message: '停止播放',
                duration: 2000,
            })
            this.isPlay = false
            logger.info(`${TAG} playAudio stop play`)
            clearInterval(this.timerPlay)
            this.audioModel.finish()
            this.millisecondPlay = 0
            this.timePlay = '00:00'
        }
    },
    complementNum(number) {
        if (number < 10) {
            return `0${number}`
        }
        return JSON.stringify(number)
    },
    //更新发送消息
    refreshMsg(){
        var that = this;
        this.MsgList = this.$app.$def.chatData[this.idx].MsgList;
        var length = this.MsgList.length;
        var n = this.num;
        this.deleteOrRecall = this.$app.$def.deleteOrRecall;

        //显示前20条对话
        //判断如果length小于20，直接显示0->20,如果大于20，则显示
        if(length - 20 * n <= 20){
            that.list = that.MsgList.slice(0,length)
        }
        else if(length - 20 * n > 20){
            that.list = that.MsgList.slice(length - 20 * (n + 1),length)
        }
        setTimeout(function(){
            that.refreshMsg();
        },2000)
    },
    socketReceive(){
        console.info("dialogPages=====RECEIVE");
        var message = this.$app.$def.mySocket.receive();
        console.info("dialogPages====message");
        if (message=='\0') {
            console.info("dialogPages=====NULL");
            return;
        }
        console.info("dialogPages=====NOTNULL:" + JSON.stringify(message));
        console.info("dialogPages=====ENTER");
//        this.dialogcontent = this.message.content;
        console.info("dialogPages=====this.chatData[this.idx].MsgList.push:" + this.MsgList);
        this.MsgList.push({isMe: false,
                    sendUid:"",
                    messageType: 0,
                    content: message,
                    profPicUrl:'/common/images/bob.jpg',
                    createTime:''});
        console.info("dialogPages=====this.chatData[this.idx].MsgList.push OK:" + this.MsgList);


    },
    //消息刷新
    //TODO 查找参数---刷新的次数
    refresh: function (e) {
        this.num++
        prompt.showToast({
            message: '刷新中...' + this.num
        })
        var that = this;
        that.fresh = e.refreshing;
//        console.info("dialogPages====refresh:" + e.lasttime);
        setTimeout(function () {
            that.fresh = false;
            var length = that.MsgList.length;
            var n = that.num;
//            var addItem = '更新元素';
            //判断如果length小于20，直接显示0->20,如果大于20，则显示
            if(length - 20 * n <= 20){
                that.list = that.MsgList.slice(0,length)
            }
            else if(length - 20 * n > 20){
                that.list = that.MsgList.slice(length - 20 * (n + 1),length)
            }
            prompt.showToast({
                message: '刷新完成!'
            })
        }, 2000)
    },
    inputChange(e){
        this.inputMsg = e.value;
    },
    onGenerateMessage(message,timestamp){
        console.info("dialogPage ====> onGenerateMessage :" + message);
        //uid:发送方
        //touid:接收方，不可为空，测试时需要改为测试客户端端口
//        let timestamp = new Date().getTime().toString()
        if(this.$app.$def.chatData[this.idx].unRead == 'say'){
            console.info("dialogPage ====> onGenerateMessage: message.type == say " );
            var obj = { uid: this.uid, touid: this.$app.$def.chatData[this.idx].uid , role:'ho_user' , type:'say', content:message, stype:0,timestamp:timestamp};
            var json = JSON.stringify(obj);
            console.log("dialogPage ====> onGenerateMessage:json == " + json);
            return json;
        }
        else if(this.$app.$def.chatData[this.idx].unRead == 'group'){
            console.info("dialogPage ====> onGenerateMessage: message.type == group " );
            var obj1 = { uid: this.uid, touid: [this.groupId] , role:'ho_user' , type:'group', content:message, stype:0,timestamp:timestamp};
            var json = JSON.stringify(obj1);
            console.log("dialogPage ====> onGenerateMessage:json == " + json);
            return json;
        }
    },
    onDestroy(){
        this.$app.$def.idx = 0;
    },
    //弹出框消失
    hidepopup() {
        this.$element("popup").hide();
        console.info("headerSearch====> popup hide");
    },
    //获取token
    getToken(){
        //取token
        var context = featureAbility.getContext()
        context.getFilesDir().then(v =>{
            dataStorage.getStorage(v + '/smart_build').then(it =>{
                let promise = it.get("token","default")
                promise.then((value) => {
                    console.info("dialogPage ====> json The value of token:" + value)
                    this.addToken = value
                }).catch((err) => {
                    console.info("dialogPage ====>Get the value of token failed with err: " + err)
                })
            })
        })
    },
    /*
	 * 开启一个定时器，来自动变换文字
	 */
    changeState(){
        //定义一个变量，用来保存定时器的标识
        var timer;
        //在开启定时器之前，需要将当前元素上的其他定时器关闭
        clearTimeout(timer);
        var that = this
        timer = setTimeout(function() {
            //修改img1的src属性
            //使索引自增
            that.changeState();
        }, 120000);
        //判断索引是否超过最大索引
        if(this.index < 2){
            this.$app.$def.deleteOrRecall = this.imgArr[this.index];
            this.index++;
        }
        else{
            clearTimeout(timer);
        }
        console.info("dialogPage ====> this.deleteOrRecall1: " + this.deleteOrRecall);

    },
    //测试接收消息信号
    testClick(){
        this.$app.$def.chatData[this.idx].MsgList.push({isMe: false,
            sendUid:"",
            messageType: 1,
            content: '/common/images/harmonyos.jpg',
            profPicUrl:'/common/images/my.jpg',
            createTime:''});
    },
    //发送消息
    clickSend(e){
        /*测试图片撤回与删除
        虚拟机测试需要解除注释*/
       /* this.$app.$def.chatData[this.idx].MsgList.push({isMe: true,
            sendUid:"",
            messageType: 1,
            content: '/common/images/harmonyos.jpg',
            profPicUrl:'/common/images/my.jpg',
            createTime:'2022/10/9'});
        this.index = 0;
        this.changeState();
        //刷新显示前20条对话，判断当前会话条数
        var length = this.MsgList.length;
        if(length <= 20){
            this.list = this.MsgList.slice(0,length)
        }
        else{
            this.list = this.MsgList.slice(length-20,length)
        }
        this.$element('chatList').scrollBottom(true);*/
        /*测试文字撤回与删除
        虚拟机测试需要解除注释*/
        /*this.$app.$def.chatData[this.idx].MsgList.push({isMe: true,
            messageType: 0,
            content: '测试',
            profPicUrl:'/common/images/my.jpg',});
        this.index = 0;
        this.changeState();*/

        if(this.inputMsg ==''){
            console.info("dialogPage ====> inputMsg is null");
            prompt.showToast({message:"输入不能为空"});
            return;
        }
        // 点击发送按钮发送消息时, 需要将textarea框里的内容放到一个变量中并把框清空，否则连发消息的时候会出现粘连
        let msgContent = this.inputMsg;
        this.inputMsg = '';
        console.info("dialogPage ====> this.addToken:  " + this.addToken);
        this.tokenCheck();
        setTimeout(() =>{
            if(this.result){
                console.info("dialogPage ====> Token is true ");
                var timestamp = new Date().getTime().toString() - 28800000;
                this.$app.$def.chatData[this.idx].MsgList.push({isMe: true,
                    sendUid:"",
                    messageType: 0,
//                    content: this.inputMsg,
                    content: msgContent,
                    profPicUrl:'/common/images/my.jpg',
                    createTime:timestamp});
                //定时器，撤回转删除
                this.index = 0;
                this.changeState();
                // 刷新显示前20条对话
                // 判断当前会话条数,少于20条截取所有会话显示;多于20条选择最后20条会话显示
                var length = this.MsgList.length;
                if(length <= 20){
                    this.list = this.MsgList.slice(0,length)
                }
                else{
                    this.list = this.MsgList.slice(length-20,length)
                }
                console.info("dialogPage ====> this.inputMsg: " + this.inputMsg);
                console.info("dialogPage ====> msgContent: " + msgContent);
                console.info("dialogPage ====> this.onGenerateMessage(msgContent):" + this.onGenerateMessage(msgContent,timestamp));
                this.$app.$def.mySocket.send(this.onGenerateMessage(msgContent,timestamp));

//                this.inputMsg = '';
                console.info("dialogPage ====> this.inputMsg = ''")
                this.$element('chatList').scrollBottom(true);
            }
            else{
                console.info("zjf == Token is false ");
                prompt.showToast({
                    message: 'token过期，请重新登录！',
                    duration: 1000,
                });
                router.push({ // 页面跳转进入注册
                    uri: "pages/login/login",
                })
            }
        },500)
    },

    send(e) {
        console.info("dialogPage ====> send:this.isAudio" + this.isAudio);
        console.info("dialogPage ====> send:this.hasSend" + this.mainData.hasSend);
        if(this.isAudio && this.mainData.hasSend === false){
            this.mainData.hasSend = true
            this.sendRecord()
        }  else {
            this.clickSend(e)
        }
    },
    /*//打开弹出框
    onListClick(msg){
        this.globalX = msg.touches[0].globalX
        this.globalY = msg.touches[0].globalY
        console.info('sessionList=====>onListClick: ' + this.globalX + "..." + this.globalY)
        this.$element("apiMenu").show({x: this.globalX,y:this.globalY});
    },*/
    //撤回、删除历史消息
    //TODO 只能撤销、删除最新消息
    deleteMsg(style,index){
        var touchId = this.touchId;
        console.info("dialogPage ====> deleteMsg:" + style + touchId );
        if(style == "删除"){
            this.$app.$def.chatData[this.idx].MsgList.splice(index,1);
            console.info("dialogPage ====> deleteMsg1");
            this.$element("popup").hide();
            console.info("dialogPage ====> deleteMsg2");
        }
        else if(style == "撤回"){
//            let timestamp = new Date().getTime().toString();
            var timestamp = this.list[index].createTime;
            console.info("dialogPage ====> recallMsg:timestamp :" + timestamp);
            if(this.$app.$def.chatData[this.idx].unRead == 'say'){
                console.info("dialogPage====>recallMsg:type == say " );
                var obj = { uid: this.uid, touid: this.$app.$def.chatData[this.idx].uid , type:'withdrawSay', content:'对方撤回了一条消息', timestamp:timestamp};
                var json = JSON.stringify(obj);
                console.info("dialogPage====>recallMsg:json == " + json);
            }
            else if(this.$app.$def.chatData[this.idx].unRead == 'group'){
                console.info("dialogPage====>recallMsg:type == group " );
                var obj = { uid: this.uid, touid: [this.groupId], type:'withdrawGroup', content:'对方撤回了一条消息', timestamp:timestamp};
                var json = JSON.stringify(obj);
                console.info("dialogPage====>recallMsg:json == " + json);
            }
            this.$app.$def.mySocket.send(json);
            let withdrawIndex = this.$app.$def.chatData[this.idx].MsgList.findIndex(item => {return item.createTime == timestamp})
            this.$app.$def.chatData[this.idx].MsgList.splice(withdrawIndex,1);
            this.$element("popup").hide();
        }
    },
    toolbar(e){
        this.$element("popup").show();
        console.info("dialogPage====> popup show :" + e);

    },

    /**
     * token过期验证
    */
    tokenCheck(){
        console.info("dialogPage ====>tokenCheckout: " + this.addToken);
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/user/checkToken", {
            method: 'POST',
            extraData:JSON.stringify({"token":this.addToken}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            prompt.showToast({
                message: '发送token成功！',
                duration: 1000,
            });
            this.user = JSON.parse(value.result.toString())
            this.result = this.user.data;
            console.info("dialogPage ====> this.result: " + this.result);
            this.code = this.user.code;
            console.info("dialogPage ====> this.code:  " + this.code);

        }).catch((err) => {
            console.error(`dialogPage ====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    //点击更多
    clickMoreBtn(){
        if(!this.showMore && !this.showFace){
            this.showMore = true;
            this.moreBtnUrl = '/common/images/fold.png'
        }
        else{
            this.moreBtnUrl = '/common/images/more.png';
            this.showMore = false;
        }
    },
    clickAudioBtn() {
      this.isAudio = !this.isAudio
    },
    clickAudio() {
      if(this.audioMsg==='点击说话'){
          this.audioMsg = '点击结束'
          this.clickRecord()
      } else if(this.audioMsg==='点击结束'){
          this.audioMsg = '点击说话'
          this.stopRecorder()
      }
    },

    //点击表情
    clickFaceBtn(){
        if(!this.showFace && !this.showMore){
            this.showFace = true;
            this.faceBtnUrl = '/common/images/keyboard.png'
            this.smiling = String.fromCodePoint(0x1F60F)
        }
        else{
            this.faceBtnUrl = '/common/images/face.png';
            this.showFace = false;
        }
    },
    clickPhoto(){
        console.info("dialogPages=====choose:start");
        var context = featureAbility.getContext()
        var media = mediaLibrary.getMediaLibrary(context);
        let option = {
            type : "image",
            count : 2
        };
        media.startMediaSelect(option, (err, value) => {
            if (err) {
                console.info("dialogPages=====An error occurred when selecting media resources." + value);
                return;
            }
            //定时器，撤回转删除
            this.index = 0;
            this.changeState();
            let IMG_URL = value.toString();
            console.info("dialogPages=====Media resources selected." + IMG_URL);
//            IMG_URL = 'dataability' + ':///media/image/1'
            //            datashare:///media/image/1
            let timestamp = new Date().getTime().toString() - 28800000
            this.$app.$def.chatData[this.idx].MsgList.push({isMe: true,
                sendUid:"",
                messageType: 1,
                content: IMG_URL,
                profPicUrl:'/common/images/my.jpg',
                createTime:timestamp});
            console.info("dialogPages=====Media resources show." + IMG_URL);
            let file1 = { filename: this.$app.$def.uid +'-'+ IMG_URL, name: 'photo', uri: IMG_URL, type: "png" };
            let imageId = this.guid()
//            let data = { imgSignature: imageId, uid: this.$app.$def.uid };
            let data = {  };
            console.info("dialogPages=====imageId:" + imageId);
            let header = { };
            let uploadTask;
            let myurl = "http://" + this.$app.$def.ip +"/file/imgUpload?imgSignature=" + imageId + "&uid=" +this.$app.$def.uid + "&imgType=" +this.$app.$def.chatData[this.idx].unRead
            console.info("dialogPages=====myurl:" + myurl);
            let _this = this
            request.upload({ url: myurl, header: header, method: "POST", files: [file1], data: [data] }).then((data) => {
                console.info("dialogPages=====request.upload.");
                uploadTask = data;
                uploadTask.on('headerReceive', function callback(headers){
                    console.info("dialogPages=====upOnHeader headers:" + JSON.stringify(headers));
                    _this.sendImage(imageId, timestamp)
                });
                //                send_once("a6/"+IMG_URL);
            }).catch((err) => {
                console.info('dialogPages=====Failed to request the upload. Cause: ' + JSON.stringify(err));
            })
        });
        console.info("dialogPages=====choose:end");
    },
    guid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
    },
    sendImage(imageId, timestamp) {
//        let timestamp = new Date().getTime().toString() - 28800000
        let obj = {}
        let json = {}
        if(this.$app.$def.chatData[this.idx].unRead == 'say'){
            console.info("dialogPages====>sendImage:type == say " );
            obj = { uid: this.uid, touid: this.$app.$def.chatData[this.idx].uid , role:'ho_user' , type:'say', content:imageId, stype:1,timestamp:timestamp};
            json = JSON.stringify(obj);
            console.info("dialogPages====>sendImage:json == " + json);
        }
        else if(this.$app.$def.chatData[this.idx].unRead == 'group'){
            console.info("dialogPages====>sendImage:type == group " );
            obj = { uid: this.uid, touid: [this.groupId] , role:'ho_user' , type:'group', content:imageId, stype:1,timestamp:timestamp};
            json = JSON.stringify(obj);
            console.info("dialogPages====>sendImage:json == " + json);
        }
        this.$app.$def.mySocket.send(json)
    },

    backToSession(){
        this.idx = 0;
        router.back();
    },
    intoChatInfo(){
        this.$app.$def.mailFriendId = -1;
        console.info("dialogPages=====intoChatInfo: " + this.$app.$def.mailFriendId);
        if(this.$app.$def.chatData[this.idx].unRead == 'say') {
            router.push({
                uri: 'pages/dialogPage/chatMessagePage/chatMessagePage',
                params: {
                    sayOrGroup: 'say',
                    sayOrGroup_ID: this.$app.$def.chatData[this.idx].uid,
                },
            });
        }
        else if(this.$app.$def.chatData[this.idx].unRead == 'group') {
            router.push({
                uri: 'pages/dialogPage/chatMessagePage/groupChatMessage',
                params: {
                    sayOrGroup: 'group',
                    sayOrGroup_ID: this.groupId,
                    isTalkForbidden: this.isTalkForbidden,
                },
            });
        }
    },
    moveImageToAlbum(imageUrl){
        //        let dest = '/storage/media/100/local/files/2.png';
        console.info('dialogPages====moveImageToAlbum start:' + imageUrl);
//        let src = '/data/app/el2/100/base/com.huawei.instantmessage_ohos/haps/entry/files/2.png';
//        let dest = '/data/app/el2/100/base/com.huawei.instantmessage_ohos/haps/entry/files/3.png';
        //getFileDic
//        let src = '/data/storage/el2/base/haps/entry/files/2.png';
//        let dest = '/data/storage/el2/base/haps/entry/files/3.png';
//        let src = './2.png';
//        let dest = './3.png';
//        let src ='internal://app/3.png'
//        let dest ='internal://app/4.png'
//        fileio.rename(src, dest).then(function(){
//            console.info('dialogPages====rename completed.');
//        }).catch(function(err){
//            console.info("dialogPages====rename failed with error:"+ err);
//            console.info("dialogPages====rename failed with error:"+ JSON.stringify(err));
//        });
        file.move({
            srcUri: 'internal://app/4.png',
            dstUri: '/storage/media/100/local/files/2.png',
            success: function(uri) {
                console.info('dialogPages====call success callback success');
            },
            fail: function(data, code) {
                console.info('dialogPages====call fail callback fail, code: ' + code + ', data: ' + data);
            },
        });
        console.info('dialogPages====moveImageToAlbum end:');
    },
    downloadImage(imageUrl) {
        let downloadTask;
        console.info('dialogPages====downloadImage start:' + imageUrl);
//        'dataability:///media/image/2'
//        internal://cache/
//        /storage/media/100/local/data/com.huawei.instantmessage_ohos/2.png
//        'internal://app/2.png'

        let context = featureAbility.getContext();
        let path = ''
        context.getFilesDir().then((data) => {
            path = data;
            console.info('dialogPages====downloadImage data:' + JSON.stringify(data));
        });
        console.info('dialogPages====downloadImage path:' + JSON.stringify(path));
        let downloadConfig = {
            url: imageUrl, // 下载地址
            header: {},                               // 下载请求Header
            enableMetered: true,                      // 允许下载
            enableRoaming: true,                      // 允许下载
//            filePath: '/storage/media/100/local/data/com.huawei.instantmessage_ohos/2.png',                       // 本地文件路径
            filePath: '/data/storage/el2/base/haps/entry/files/2.png',                       // 本地文件路径
            networkType: request.NETWORK_WIFI         // WIFI网络下载
        }
//        { url: imageUrl, filePath:'internal://cache/' }
        request.download(downloadConfig, (err, data) => {
            if (err) {
                console.error('dialogPages====Failed to request the download. Cause: ' + JSON.stringify(err));
                return;
            }
            downloadTask = data;
            console.info('dialogPages====downloadImage get downloadTask');
            //下载完成
            console.info('dialogPages====ready to on complete');
            downloadTask.on('complete', function callback() {
                console.info('dialogPages====Download task completed.');
                //copyfile
//                let src = '/data/storage/el2/base/haps/entry/files/2.png';
//                let src = '/data/app/el2/100/base/com.huawei.instantmessage_ohos/haps/entry/files/2.png';
//                let dest = '/storage/media/100/local/files/';
//                fileio.copyFile(src, dest).then(function(){
//                    console.info('dialogPages====fileio completed.');
//                }).catch(function(err){
//                    console.info("dialogPages====copyFile failed with error:"+ err);
//                    console.info("dialogPages====copyFile failed with error:"+ JSON.stringify(err));
//                });
                prompt.showToast({
                    message: '下载图片成功！',
                    duration: 1000,
                });
            });
            //下载失败
            console.info('dialogPages====ready to on fail');
            downloadTask.on('fail', function callBack(err) {
                console.info('dialogPages====Download task failed. Cause:' + err);
            });
            //下载进度
            console.info('dialogPages====ready to on process');
            downloadTask.on('progress', function download_callback(receivedSize, totalSize) {
                console.info("dialogPages====download receivedSize:" + receivedSize + " totalSize:" + totalSize);
            });
            console.info('dialogPages====downloadImage end');
        });

//        let downloadTask;
//        console.info('dialogPages====downloadImage start:' + imageUrl);
//        //下载
//        request.download({ url: imageUrl, filePath:'workspace/' }).then((data) => {
//            downloadTask = data;
//            console.info('dialogPages====downloadImage get downloadTask');
//            //下载完成
//            console.info('dialogPages====ready to on complete');
//            downloadTask.on('complete', function callback() {
//                console.info('dialogPages====Download task completed.');
//                prompt.showToast({
//                    message: '下载图片成功！',
//                    duration: 1000,
//                });
//            });
//            //下载失败
//            console.info('dialogPages====ready to on fail');
//            downloadTask.on('fail', function callBack(err) {
//                console.info('dialogPages====Download task failed. Cause:' + err);
//            });
//            //下载进度
//            console.info('dialogPages====ready to on process');
//            downloadTask.on('progress', function download_callback(receivedSize, totalSize) {
//                console.info("dialogPages====download receivedSize:" + receivedSize + " totalSize:" + totalSize);
//            });
//            console.info('dialogPages====downloadImage end');
//        }).catch((err) => {
//            console.info('dialogPages====Failed to request the download. Cause: ' + JSON.stringify(err));
//        })
    },
    clickFile() {
        router.push({
            uri: "pages/fileSelect/fileSelect",
            params: {
                "idx": this.idx,
            }
        });
    },
    downloadFile(fileUrl) {
        let downloadTask;
        console.info('dialogPages====downloadFile start from : ' + fileUrl);
        let fileFullName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        let fileSuffix = fileFullName.substring(fileFullName.lastIndexOf(".") + 1);
        let fileName = fileFullName.substring(0, fileFullName.lastIndexOf("."));
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hour = date.getHours();
        let minute = date.getMinutes();
        let second = date.getSeconds();
        let downloadTime = year + "-" + month + "-" + day + "_" + hour + "-" + minute + "-" + second;
        console.info("dialogPages=====downloadTime : " + downloadTime);
        let downloadFileName = fileName + "_" + downloadTime + "." + fileSuffix;
        let downloadConfig = {
            url: fileUrl, // 下载地址
            header: {}, // 下载请求Header
            enableMetered: true, // 允许下载
            enableRoaming: true, // 允许下载
            filePath: '/data/storage/el2/base/haps/entry/files/' + downloadFileName, // 本地文件路径
            //            /data/app/el2/100/base/com.huawei.instantmessage_ohos/haps/entry/files/   // 下载后存放的路径
            networkType: request.NETWORK_WIFI // WIFI网络下载
        }
        request.download(downloadConfig, (err, data) => {
            if (err) {
                console.error('dialogPages====Failed to request the download. Cause: ' + JSON.stringify(err));
                return;
            }
            downloadTask = data;
            console.info('dialogPages====downloadFile : get downloadTask');
            //下载完成
            downloadTask.on('complete', function callback() {
                console.info("dialogPages=====into complete function");
                console.info('dialogPages====Download task completed.');
                prompt.showToast({
                    message: '下载文件成功！',
                    duration: 1000,
                });
                console.info('dialogPages====downloadFile end');
            });
            //下载失败
            downloadTask.on('fail', function callBack(err) {
                console.info("dialogPages=====into fail function");
                console.info('dialogPages====Download task failed. Cause:' + err);
            });
            //下载进度
            downloadTask.on('progress', function download_callback(receivedSize, totalSize) {
                console.info("dialogPages=====into progress function");
                console.info("dialogPages====download receivedSize:" + receivedSize + " totalSize:" + totalSize);
            });
            console.info("dialogPages=====Before query")
            downloadTask.query((err, downloadInfo) => {
                if (err) {
                    console.error('dialogPages=====Failed to query. Cause:' + JSON.stringify(err));
                } else {
                    console.info('dialogPages=====query success! downloadInfo : ' + JSON.stringify(downloadInfo));
                }
            });
        });
    },
}
